package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.MarketingAccountApiService;
import com.yixun.qfbao.apidto.v10dto.BindMarketingAccountReqDto;
import com.yixun.qfbao.apidto.v10dto.MarketingBaseResponseDto;
import com.yixun.qfbao.apidto.v10dto.MarketingPhoneResDto;
import com.yixun.qfbao.config.V10ApiConfig;
import com.yixun.qfbao.config.V10InterfaceAddr;
import com.yixun.qfbao.mapper.MarketingAccountMapper;
import com.yixun.qfbao.mapper.MarketingAccountUseinfoMapper;
import com.yixun.qfbao.model.MarketingAccount;
import com.yixun.qfbao.model.MarketingAccountUseinfo;
import com.yixun.qfbao.model.dto.MarketingAccountDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.MarketingAccountEnum;
import com.yixun.qfbao.util.HttpApi;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.PremisesMapper;
import com.yixun.qfbao.xf.model.Premises;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class MarketingAccountApiServiceImpl implements MarketingAccountApiService {
    public static final String marketingPlatform = "channel";

    public static final String marketingUserUuid = "manger-auth";

    public static final String marketingSystemCategory = "v10";

    @Autowired
    MarketingAccountMapper mapper;
    @Autowired
    PremisesMapper premisesMapper;
    @Autowired
    MarketingAccountUseinfoMapper marketingAccountUseinfoMapper;
    @Autowired
    V10ApiConfig v10ApiConfig;

    /**
     *绑定营销号
     * @param premisesId
     * @param phoneNo
     * @return
     */
    @Override
    @Transactional
    public String bindMarketingAccount(Long premisesId,String phoneNo) {
        // 从营销号中随机选出一个号码，绑定到楼盘中
        MarketingAccountDto marketingAccountDto = new MarketingAccountDto();
        marketingAccountDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        marketingAccountDto.setIsUsed(MarketingAccountEnum.NOT_USE.getNo());
        marketingAccountDto.setIsValid(MarketingAccountEnum.IS_VALID.getNo());
        List<MarketingAccount> marketingAccountList = mapper.selectListByDto(marketingAccountDto);
        //获取楼盘
        Premises selectPremises = premisesMapper.selectById(premisesId);
        if(marketingAccountList == null || marketingAccountList.size() == 0){
            //没有可用的营销号
            throw  new TServerException("没有可用的营销号");
        }
        // todo 调用电话接口
        MarketingBaseResponseDto resDto =  bindMarketingAccount(marketingAccountList.get(0).getAccount(),selectPremises.getMobile(),"1");
        if(!"0".equals(resDto.getErrorCode())){
            throw  new TServerException("绑定营销号失败" + resDto.getErrorMessage());
        }

        //调用接口成功之后 更新楼盘
        Premises premises = new Premises();
        premises.setId(premisesId);
        premises.setMarketingNumber(marketingAccountList.get(0).getAccount());
        premisesMapper.updateMarketingNumber(premises);
        //更新营销号码池中使用情况
        MarketingAccount marketingAccount = new MarketingAccount();
        marketingAccount.setId(marketingAccountList.get(0).getId());
        marketingAccount.setIsUsed(MarketingAccountEnum.IS_USE.getNo());
        marketingAccount.setUpdateTime(Calendar.getInstance().getTime());
        mapper.edit(marketingAccount);

        // 记录useInfo
        MarketingAccountUseinfo marketingAccountUseinfo = new MarketingAccountUseinfo();
        marketingAccountUseinfo.setAccountId(marketingAccountList.get(0).getId());
        marketingAccountUseinfo.setUserType(MarketingAccountEnum.USER_TYPE_BIND.getNo());
        marketingAccountUseinfo.setObjectId(premisesId);
        marketingAccountUseinfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
        marketingAccountUseinfo.setCreateTime(Calendar.getInstance().getTime());
        marketingAccountUseinfoMapper.add(marketingAccountUseinfo);

        return marketingAccountList.get(0).getAccount();
    }

    /**
     * 解绑营销号
     * @param premisesId
     * @return
     */
    @Transactional
    @Override
    public String unBindMarketingAccount(Long premisesId) {
        Premises premises = premisesMapper.selectById(premisesId);
        if(premises == null){
            throw  new TServerException("未获取到楼盘");
        }
        if(StringUtils.isBlank(premises.getMarketingNumber())){
            throw  new TServerException("楼盘未绑定营销号");
        }

        //删除楼盘营销号
        String marketingNumber = premises.getMarketingNumber();
        premises.setMarketingNumber("");
        premisesMapper.updateMarketingNumber(premises);
        //更新营销号码池状态
        MarketingAccountDto marketingAccountDto = new MarketingAccountDto();
        marketingAccountDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        marketingAccountDto.setAccount(marketingNumber);
        List<MarketingAccount> marketingAccountList = mapper.selectListByDto(marketingAccountDto);
        if(marketingAccountList == null || marketingAccountList.size() == 0){
            throw  new TServerException("未查询到营销号信息");
        }
        //  调用电话接口
        MarketingBaseResponseDto resDto =  bindMarketingAccount(marketingNumber,premises.getMobile(),"2");
        if(!"0".equals(resDto.getErrorCode())){
            throw  new TServerException("解绑营销号失败" + resDto.getErrorMessage());
        }

        MarketingAccount updateMarketingAccount = new MarketingAccount();
        updateMarketingAccount.setId(marketingAccountList.get(0).getId());
        updateMarketingAccount.setIsUsed(MarketingAccountEnum.NOT_USE.getNo());
        mapper.edit(updateMarketingAccount);

        //更新useInfo
        MarketingAccountUseinfo marketingAccountUseinfo = new MarketingAccountUseinfo();
        marketingAccountUseinfo.setAccountId(marketingAccountList.get(0).getId());
        marketingAccountUseinfo.setUserType(MarketingAccountEnum.USER_TYPE_UNBIND.getNo());
        marketingAccountUseinfo.setObjectId(premisesId);
        marketingAccountUseinfo.setCreateTime(Calendar.getInstance().getTime());
        marketingAccountUseinfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
        marketingAccountUseinfoMapper.add(marketingAccountUseinfo);

        return marketingAccountList.get(0).getAccount();
    }

    /**
     * 获取绑定营销号
     * @return
     */
    @Override
    public MarketingPhoneResDto findDindPhone(){
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("token",v10ApiConfig.getV10MarketingToken());
        String result = HttpApi.doPostMarketing(v10ApiConfig.getV10MarketingUrl() + V10InterfaceAddr.findDingdingPhoneByAccountId,JSONObject.toJSONString(reqMap));
        MarketingPhoneResDto resDto = JSONObject.parseObject(result,MarketingPhoneResDto.class);

        return resDto;
    }

    /**
     * 绑定营销号
     * @param adTel
     * @param called
     * @param bindStatus 1 绑定，2 解绑
     * @return
     */
    private MarketingBaseResponseDto bindMarketingAccount(String adTel,String called,String bindStatus){
        if(called == null){
            throw  new TServerException("绑定号码不能为空");
        }
        Map<String,Object> reqMap = new HashMap<>();
        List<BindMarketingAccountReqDto> list = new ArrayList<>();
        BindMarketingAccountReqDto reqDto = new BindMarketingAccountReqDto();
        reqDto.setPlatform(marketingPlatform);
        reqDto.setAdtel(adTel);
        reqDto.setCalled(called);
        reqDto.setSystemCategory(marketingSystemCategory);
        reqDto.setBind(bindStatus);
        reqDto.setUserUuid(marketingUserUuid);
        reqDto.setMontheRent("");
        reqDto.setShutdownTime("");
        reqDto.setRentUsedTime("");
        reqDto.setShowPhone("");
        reqDto.setAccountId("");

        list.add(reqDto);
        reqMap.put("phoneList",list);
        reqMap.put("token",v10ApiConfig.getV10MarketingToken());

        String  result = HttpApi.doPostMarketing(v10ApiConfig.getV10MarketingUrl() + V10InterfaceAddr.saveMarketingPhone, JSONObject.toJSONString(reqMap));
        MarketingBaseResponseDto resDTO = JSONObject.parseObject(result,MarketingBaseResponseDto.class);
        return resDTO;
    }
}
